import React, { useEffect, useState, useRef } from "react";
// 引入socket
import { Socket, io } from "socket.io-client";
//提示
import { message } from "antd";

import styles from "./catch.less";
//定义颜色 
const COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];

// 定义提示的 接口
interface IMessage {
    username: string,
    message: string,
}
// 定义一下Socket的实例
let socket: Socket;
const Catch: React.FC = () => {
    // 定义用户的信息数组
    const [messages, setMessages] = useState<IMessage[]>([]);
    // 受控输入框
    const [text, setText] = useState("");
    const [username, setUsername] = useState("")
    // 开关
    const [isAddUser, setIsAddUser] = useState(false);
    // 获取标签元素
    const messageList=useRef<HTMLElement>(null);
    // 监听消息列表,让页面自动滚到最下方
    useEffect(()=>{
        if(!messageList.current){
           return 
        }
        console.log(messageList,messageList.current?.scrollHeight);
    },[message])

    useEffect(()=>{
        if(socket){
                return
        }
        //建立socket实例
        socket=io("http://10.0.8.5:8000/");
        // 监听链接成功
        socket.on('connent',()=>{
            console.log("听说这是链接成功");
            socket.emit('add user',username);
        })
        // 监听message用户信息数组
        // 只有写到这一步 才能被真正看到
        socket.on('new message',(res:IMessage)=>{
            setMessages(messages=>[...messages,res]);
        });
        // 监听用户进入聊天室
        socket.on('user joined',(data)=>{
            console.log('data...',data);
            let message='';
            console.log(message);
            if(data.numUsers===1){
                console.log(111);
                    message+=`已有一名用户进入聊天室`
            }else{
                message+=`已有${data.numUsers}用户进入聊天室`
            }
            setMessages(messages=>[...messages,({...data,message})]);
        })
    },[])
    // 随机获取用户名的颜色  
    function getUsernameColor(){
        let index=Math.floor(Math.random()*12);
        return COLORS[index];
    }
    // 处理用户发消息
    function handleKeyDowm(e:React.KeyboardEvent<HTMLInputElement>){
        if(e.keyCode===13){
            if(!text){
                 message.warn('pleace input your message');
                 return 
            }
               setMessages([...messages,{message:text,username}]);
               socket.emit('new message',text);
        }
    }
    // 处理用户昵称
    function handleUserKeyDown(e:React.KeyboardEvent<HTMLInputElement>){
        if(e.keyCode===13){
                if(!username){
                        message.warn("pleasse input your nick Name");
                        return;
                }
                socket.emit('add user',username);
        
                setIsAddUser(true);
        }
    }


    return <div className={styles.container}>
       {!isAddUser ? <section className={styles.wrap}>
            <span>请输入你的姓名?</span>
            <input type="text" value={username} onChange={e => setUsername(e.target.value)} onKeyDown={e => handleUserKeyDown(e)} />
        </section> :
        <section className={styles.chat}>
            <section className={styles.list} ref={messageList}>
                {messages && messages.map((item, index) => {
                    return <p key={index}>
                        <span style={{ color: getUsernameColor() }}>{item.username}</span>
                        <span>{item.message}</span>
                    </p>
                })}
            </section>
            <section>
                <input type="text" value={text} onChange={e => setText(e.target.value)} onKeyDown={e => handleKeyDowm(e)} />
            </section>
        </section>}
    </div>
}

export default Catch




